let eventSourceTask;

Page({
  data: {
    eventSourceStatus: '',
    text: ''
  },
  createEventSource() {
    const eventSourceStatus = this.data.eventSourceStatus;
    if (eventSourceTask && eventSourceStatus === 'open') return;
    if (eventSourceTask && eventSourceStatus && eventSourceStatus !== 'open') eventSourceTask.close();
    const url = "https://dingvip.com/index.php?input=山西省阳泉'";
    eventSourceTask = tt.createEventSource({ url });
    eventSourceTask.onOpen(() => {
      console.log('已连接');
      this.setData({
        eventSourceStatus: 'open'
      });
    });

    eventSourceTask.onClose(() => {
      console.log('eventSource 已断开');
      this.setData({
        eventSourceStatus: 'close'
      });
    });

    eventSourceTask.onError((error) => {
      console.error('eventSource 发生错误:', error);
      this.msg('发生错误');
      this.setData({
        eventSourceStatus: 'error'
      });
    });

    eventSourceTask.onMessage((res) => {
      console.log('eventSource res:', res.data); // 添加调试日志
      if (res.data === '[DONE]') {
        console.log('eventSource 完成');
        this.closeEventSource();
        return;
      }

      try {
        const jsondata = JSON.parse(res.data);
        if (jsondata && jsondata.choices && jsondata.choices[0] && jsondata.choices[0].delta && jsondata.choices[0].delta.content) {
          const content = jsondata.choices[0].delta.content;
          const formattedContent = content
          // .replace(/\n/g, '</br>')
          // .replace(/---/g, '</br>');
          if (formattedContent) {
            const newContent = ` ${formattedContent}`
              .replace(/\n/g, '<br>')
              .replace(/###([^#]+)###/g, '<div style="text-align: left;">$1</div>')
              .replace(/\*\*([^*]+)\*\*/g, '<b>$1</b>')
              .replace(/---/g, '');

            this.setData({
              text: this.data.text + newContent
            });
          }
        } else {
          console.warn('Received unexpected JSON structure:', jsondata);
        }
      } catch (error) {
        console.error('解析 JSON 数据时出错:', error);
        this.msg('解析数据时发生错误');
      }
    });
  },
  closeEventSource() {
    if (eventSourceTask) {
      eventSourceTask.close({
        success: res => {
          console.log('close eventSource success', res);
          tt.showToast({
            title: 'close success',
            content: JSON.stringify(res),
          });
          this.setData({
            eventSourceStatus: 'close'
          });
        },
        fail: err => {
          console.log('close eventSource err', err);
        }
      });
    }
  },
  // 清空数据
  clearData() {
    this.setData({
      text: ''
    });
  },
  msg(msg) {
    tt.showToast({
      title: msg,
      icon: 'none'
    });
  },
});
